let express = require('express'); //引入express
let Mock = require('mockjs'); //引入mock
let markdown = require('markdown').markdown;
const cors = require('cors'); // 处理跨域
const bodyParser = require('body-parser');
let app = express(); //实例化express
const fs = require('fs');
const path = require('path');
const PORT = 8090; //默认端口
app.use(cors());

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());

/**
 *
 * 获取对应的文档，做展示处理
 */
app.get('/api/docs/:name', (req, res) => {
  let filePath = path.resolve(__dirname, '../docs') + '/' + req.params.name + '.md';
  fs.readFile(filePath, (err, data) => {
    if (err) {
      res.json({
        success: false,
        msg: '找不到文件',
      });
    } else {
      res.send({
        success: true,
        data: markdown.toHTML(data.toString()),
      });
    }
  });
});

app.get('/api/tableList', (req, res) => {
  const { size } = req.query;
  let target = `tableData|${size}`;
  let param = {};
  param[target] = [
    {
      'id|1-100': 1,
      'name|1': [
        Mock.Random.name(),
        Mock.Random.name(),
        Mock.Random.name(),
        Mock.Random.name(),
        Mock.Random.name(),
      ],
      'email|1': [
        Mock.Random.email(),
        Mock.Random.email(),
        Mock.Random.email(),
        Mock.Random.email(),
        Mock.Random.email(),
        Mock.Random.email(),
      ],
      'address|1': [
        Mock.Random.city(),
        Mock.Random.city(),
        Mock.Random.city(),
        Mock.Random.city(),
        Mock.Random.city(),
        Mock.Random.city(),
        Mock.Random.city(),
      ],
    },
  ];
  setTimeout(() => {
    res.json({
      success: true,
      data: Mock.mock({
        ...param,
        total: 100,
      }),
    });
  }, 500);
});
app.listen(PORT, () => {
  console.log('监听端口' + PORT);
});
